package com.hd.trans.share;

import android.text.TextUtils;

import com.hd.trans.R;
import com.hd.trans.ui.base.AppContextProvider;

import java.io.File;
import java.util.List;

import io.reactivex.rxjava3.core.Observable;

/**
 * 读取 .txt/.srt文件
 */
public class SrtFileToTextRequest {
    public Observable<String> request(File file){
        if(!file.exists()){
            return Observable.just("");
        }
        String fileName = file.getName();
        String content = "";
        if(fileName.endsWith(".txt")){ // 内容文件是txt格式
            content = FileRWExtUtil.readFileOnLine(file.getAbsolutePath());
        }else if(fileName.endsWith(".srt")){
            List<Subtitle> subtitles = SRTParser.getSubtitlesFromFile(file.getAbsolutePath(),false);
            if(subtitles.size()<=0){
                content = "";
            }else{
                StringBuffer stringBuffer = new StringBuffer();
                for (Subtitle subtitle : subtitles){
                    stringBuffer.append(subtitle.getText());
                }
                content = stringBuffer.toString();
            }
        }
        if(TextUtils.isEmpty(content)){
            return Observable.error(new HuDunThrowable(AppContextProvider.getContext().getString(R.string.read_text_fail)));
        }else{
            return Observable.just(content);
        }
    }
}
